﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CommClass;

namespace DMS
{
    public partial class FrmOpenInventory : DMS.FrmTemplate
    {
        DataConnection dc = new DataConnection();
        DataSource dsExcelFile;
        public FrmOpenInventory()
        {
            InitializeComponent();
        }

        private void FrmOpenInventory_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.Filter = "Excel文件|*.xls;*.xlsx|所有文件|*.*";

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                this.tbFileName.Text = dlg.FileName;
                dlg.Dispose();
                dc.DBName = tbFileName.Text;
                dsExcelFile = new ExcelDataSource(dc);
                cbbSheets.DataSource = dsExcelFile.GetTableNames();
                cbbSheets.SelectedIndex = 0;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //显示excel数据
            dvgOpeningInventory.DataSource = dsExcelFile.GetRecord("select * from [" + cbbSheets.Text + "]").Tables[0];

            this.button3.Enabled = true;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)dvgOpeningInventory.DataSource;
            Stock st = new Stock();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                st.AccountPeriod = dt.Rows[i][0].ToString();
                st.ProdID = App.GetProdIDByCode(dt.Rows[i][3].ToString());
                st.StorageID = App.GetStorageID(dt.Rows[i][1].ToString());
                st.SupplierID = App.GetSupplierID(dt.Rows[i][2].ToString());
                st.Batch = dt.Rows[i][4].ToString();
                st.StockQty = Decimal.Parse(dt.Rows[i][5].ToString());
                st.Remark = dt.Rows[i][6].ToString();

                if (st.ProdID > 0 && st.StorageID > 0 && st.SupplierID > 0)
                {
                    if (!App.SaveOpeningInventory (st))
                    {
                        lstInfo.Items.Add("库位：" + dt.Rows[i][1].ToString() + ",货权公司：" + dt.Rows[i][2].ToString() + ",品项：" + dt.Rows[i][3].ToString() + ",批次:" + dt.Rows[i][4].ToString() + ",数据重复或数据类型错误。请核查！");
                    }
                }
                else
                {
                    lstInfo.Items.Add("库位：" + dt.Rows[i][1].ToString() + ",货权公司：" + dt.Rows[i][2].ToString() + ",品项：" + dt.Rows[i][3].ToString() + ",批次:" + dt.Rows[i][4].ToString() + ",有数据与系统信息不匹配。请核查！");
                }
            }
            lstInfo.Items.Add("数据导入完成！");
        }

        private void button4_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
